! ----------------------------------------------------------
! Programmer:   Jonathan Landrum
! Date:         17 February 2012
! ----------------------------------------------------------
! Program:      padovanSequence.f95
! Purpose:      Calculates the Padovan Sequence.
! Assumptions:  None.
! ----------------------------------------------------------

PROGRAM padovanSequence

	IMPLICIT NONE

	INTEGER   :: counter = 0, input = 0, padovan

	WRITE (*,*) '* * * * * * * * * * * * * * * * * * * * * * *'
	WRITE (*,*) '*                                           *'
	WRITE (*,*) '*     FORTRAN PADOVAN SEQUENCE GENERATOR    *'
	WRITE (*,*) '*                                           *'
	WRITE (*,*) '* * * * * * * * * * * * * * * * * * * * * * *'
	WRITE (*,*)
	WRITE (*,*) 'This program calculates and returns members'
	WRITE (*,*) 'of the Padovan Sequence.'
	WRITE (*,*)
	WRITE (*,*) 'How many Padovan Numbers would like to return?'
	WRITE (*,*)
	READ  (*,*) input
		
	! If the user inputs a negative number, ask again
	DO WHILE (input < 0)
		WRITE (*,*)
		WRITE (*,*) 'ERROR: Negative input'
		WRITE (*,*)
		WRITE (*,*) 'How many Padovan Numbers would like to return?'
		WRITE (*,*)
		READ  (*,*) input
	END DO
	! END while negative
	
	WRITE (*,*)
	WRITE (*,*) '--------------------------------------------------'
		
	! We have a legitimate number, do the calculation
	DO WHILE (counter < input)
		WRITE (*,*) padovan(counter)
		counter = counter + 1
	END DO
	! END Processing loop
	
	WRITE (*,*) '--------------------------------------------------'
	WRITE (*,*)
	WRITE (*,*) '\\//_ Live long and prosper.'
	WRITE (*,*)
END PROGRAM padovanSequence

! ----------------------------------------------------------
! FUNCTION padovan:
! Calculates and returns the integer of the Padovan Sequence
! at the specified input position. The sequence is:
! 1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12, 16, 21, 28, 37, 49, etc.
! ----------------------------------------------------------

RECURSIVE FUNCTION padovan (input) RESULT (output)
	IMPLICIT NONE

	INTEGER :: input
	INTEGER :: output

	IF (input > 2) THEN
		output = padovan(input - 2) + padovan(input - 3)
	ELSE
		output = 1
	END IF
	
END FUNCTION padovan